import { defineStore } from 'pinia'
import articleAPI from '../api/article'

export const useArticleStore = defineStore('article', {
  state: () => ({
    articles: [],
    currentArticle: null,
    loading: false,
    error: null,
    pageInfo: {
      total: 0,
      pageNum: 1,
      pageSize: 10
    }
  }),

  getters: {
    getArticleById: (state) => (id) => {
      return state.articles.find(article => article.id === id)
    }
  },

  actions: {
    // 创建文章
    async createArticle(articleData) {
      this.loading = true
      this.error = null
      try {
        const response = await articleAPI.createArticle(articleData)
        if (response.code === 200) {
          this.articles.unshift(response.data)
          return response.data
        } else {
          throw new Error(response.message || '创建文章失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新文章
    async updateArticle(id, articleData) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型
        const numericId = typeof id === 'string' ? Number(id) : id
        const response = await articleAPI.updateArticle(numericId, articleData)
        if (response.code === 200) {
          const index = this.articles.findIndex(article => String(article.id) === String(id))
          if (index !== -1) {
            this.articles[index] = response.data
          }
          if (this.currentArticle && String(this.currentArticle.id) === String(id)) {
            this.currentArticle = response.data
          }
          return response.data
        } else {
          throw new Error(response.message || '更新文章失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取文章详情
    async fetchArticleById(id) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型，避免字符串ID导致查询问题
        const numericId = typeof id === 'string' ? Number(id) : id
        const response = await articleAPI.getArticleById(numericId)
        if (response.code === 200) {
          this.currentArticle = response.data
          return response.data
        } else {
          throw new Error(response.message || '获取文章失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除文章
    async deleteArticle(id) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型
        const numericId = typeof id === 'string' ? Number(id) : id
        const response = await articleAPI.deleteArticle(numericId)
        if (response.code === 200) {
          // 使用String比较避免类型不匹配
          this.articles = this.articles.filter(article => String(article.id) !== String(id))
          if (this.currentArticle && String(this.currentArticle.id) === String(id)) {
            this.currentArticle = null
          }
          return true
        } else {
          throw new Error(response.message || '删除文章失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取文章列表
    async fetchArticleList() {
      this.loading = true
      this.error = null
      try {
        const response = await articleAPI.getArticleList()
        if (response.code === 200) {
          this.articles = response.data
          return response.data
        } else {
          throw new Error(response.message || '获取文章列表失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 分页获取文章
    async fetchArticlePage(pageNum = 1, pageSize = 10) {
      this.loading = true
      this.error = null
      try {
        const response = await articleAPI.getArticlePage(pageNum, pageSize)
        if (response.code === 200 && response.data) {
          this.articles = response.data.records || []
          this.pageInfo = {
            total: response.data.totalRow || 0,
            pageNum: pageNum,
            pageSize: pageSize
          }
          return response.data
        } else {
          throw new Error(response.message || '分页获取文章失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 重置错误
    clearError() {
      this.error = null
    }
  }
})